# coding=utf-8

import akshare as ak
import pandas as pd
from loguru import logger


def get_sh_pct_dict_down_date():
    # 获取上证涨跌幅度字典
    sh_pct_dict = dict()
    df_sh = pd.read_csv('shanghai_index.csv')
    df_sh_list = df_sh.to_dict(orient='records')
    sh_dict = {}
    for item in df_sh_list:
        trade_date = str(item.get('日期')).replace('-', '')
        pct = float(item.get('涨跌幅'))
        sh_dict[trade_date] = item
        sh_pct_dict[trade_date] = pct

    return list(sh_dict.keys()), sh_pct_dict


def get_sh_down_date():
    # 获取上证涨跌幅度字典
    df_sh = pd.read_csv('shanghai_index.csv')
    df_sh_list = df_sh.to_dict(orient='records')
    sh_dict = {}
    for item in df_sh_list:
        trade_date = str(item.get('日期')).replace('-', '')
        sh_dict[trade_date] = item
    return sh_dict, list(sh_dict.keys())


def get_bkd_today(bkd=0):
    if not bkd:
        sz_index_df = ak.stock_zh_index_daily(symbol="sh000001")
        df_sorted = sz_index_df.sort_values(by='date', ascending=False)
        df_sorted.to_csv("shanghai_index_new.csv", index=False)
    else:
        df_sorted = pd.read_csv('shanghai_index_new.csv')
    today_date = eval(str(list(df_sorted['date'])[bkd]).replace('-', ''))
    return today_date


def down_sh_new():
    logger.info('更新开始 shanghai_index_new.csv')
    sz_index_df = ak.stock_zh_index_daily(symbol="sh000001")
    df_sorted = sz_index_df.sort_values(by='date', ascending=False)
    df_sorted.to_csv("shanghai_index_new.csv", index=False)
    logger.success('更新完成 shanghai_index_new.csv')


def down_sh():
    down_sh_new()
    logger.info('更新开始 shanghai_index.csv')
    old_csv = 'shanghai_index.csv'
    new_csv = 'shanghai_index_new.csv'
    df_old = pd.read_csv(old_csv)
    df_new = pd.read_csv(new_csv)
    logger.info(f'old={df_old.iloc[0, 0]}, new={df_new.iloc[0, 0]}')
    if df_old.iloc[0, 0] != df_new.iloc[0, 0]:
        sz_index_df = ak.index_zh_a_hist(symbol="000001", period="daily")
        df_sorted = sz_index_df.sort_values(by='日期', ascending=False)
        df_sorted.to_csv(old_csv, index=False)
    logger.success(f'更新完成 {old_csv}')


if __name__ == '__main__':
    down_sh()
